package com.okaixz.client.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.okaixz.client.model.domain.DuJiTang;
import com.okaixz.client.mapper.DuJiTangMapper;
import com.okaixz.client.service.IDuJiTangService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.okaixz.common.constant.CommonConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.Random;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author cdz
 * @since 2025-09-02
 */
@Service
@Slf4j
public class DuJiTangServiceImpl extends ServiceImpl<DuJiTangMapper, DuJiTang> implements IDuJiTangService {

    @Override
    public DuJiTang getOne() {
        // 1. 获取主键最小值和最大值
        int count = count();

        log.info("count:{}", count);

        // 2. 转换ID范围
        Long minId = 16l;
        Long maxId = minId+count;

        return getRandomDataWithRetry(minId, maxId, 3);
    }
    /**
     * 带重试机制的随机查询（避免ID不连续导致的空结果）
     */
    private DuJiTang getRandomDataWithRetry(Long minId, Long maxId, int retryCount) {
        if (retryCount <= 0) {
            // 重试次数耗尽时，使用传统随机排序兜底
            return lambdaQuery().eq(DuJiTang::getStatus, CommonConstants.STATUS_ENABLE)
                    .eq(DuJiTang::getId, 18)
                    .one()
                    ;
        }
        Long randomId = RandomUtil.getRandom().nextLong(minId, maxId);
        DuJiTang entity = getById(randomId);

        return entity != null ? entity : getRandomDataWithRetry(minId, maxId, retryCount - 1);
    }

}
